#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
# @Time : 2020/3/29 9:15 下午 
# @Author : Aries 
# @Site :  
# @File : wyy.py 
# @Software: PyCharm
import os
import re
from multiprocessing.pool import Pool

import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent

import platform

HEADERS = {
    'user-agent': UserAgent().random
}


def getResponse(url, headers=None):
    if headers is None:
        headers = HEADERS
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response
        return None
    except Exception as e:
        return None


def getSongName(songid):
    url = 'http://music.163.com/m/song?id={}'.format(songid)
    text = getResponse(url, HEADERS).text
    soup = BeautifulSoup(text, 'lxml')
    title = soup.title.text
    name = title.split('-')[0].strip()
    return name


# 获取每个歌单的URL
def getHotList():
    url = 'https://music.163.com/discover/playlist/?order=hot'
    text = getResponse(url, HEADERS).text
    '<a title="国摇金属:梦与花火怒放的桀骜篇章" href="/playlist?id=3114158828" class="msk"></a>'
    songids = re.findall(r'<a title="(.*?)" href="/playlist\?id=(\d+)" class="msk"></a>', text)
    'https://music.163.com/playlist?id=3114158828'
    data = [(x, 'https://music.163.com/playlist?id={}'.format(y)) for x, y in songids]

    pool = Pool(processes=4)
    pool.map(getPlaylist, data)


def mkdir(uri):
    if platform.system() == 'Darwin':
        # Mac
        uri = os.path.join(r'/Users/hoipeng/Music/网易云音乐/', uri)
    else:
        # 群晖
        uri = os.path.join(r'/volume1/music/网易云热门歌单/', uri)

    if not os.path.exists(uri):
        os.makedirs(uri)
    return uri


# 获取每个歌单中的歌曲
def getPlaylist(data):
    uri = mkdir(data[0].replace('/', '\\'))
    text = getResponse(data[1], headers=HEADERS).text
    # '<a href="/song?id=381954"><b title="不要逃避">不<div class="soil">火走</div>要逃避</b></a>'
    songids = re.findall(r'<a href="/song\?id=(\d+)">(.*?)</a>', text)
    # songids = re.findall(r'href="/artist\?id=(.*?)" hidefocus="true">', text)

    for i in songids:
        download_url = 'http://music.163.com/song/?id={}'.format(i[0])
        text2 = getResponse(download_url, headers=HEADERS).text
        ss = re.findall(r'<a class="s-fc7" href="/artist\?id=(\d+)">(.*?)</a>', text2)
        print(ss)

    # for i in songids:
    #     download_url = 'http://music.163.com/song/media/outer/url?id={}'.format(i[0])
    #     try:
    #         with open(r'{}/{}.mp3'.format(uri, i[1]), 'wb') as f:
    #             f.write(requests.get(download_url, headers=HEADERS).content)
    #         print('*' * 10 + ' {}下载完成'.format(i[1]))
    #     except FileNotFoundError:
    #         pass
    #     except OSError:
    #         pass

    # print('*' * 20 + '下载完成' + '*' * 20)


if __name__ == '__main__':
    getHotList()
